module.exports = (app) => {
  const express = require("express");
  const jwt = require("jsonwebtoken");
  const assert = require("http-assert");
  const AdminUser = require("../../models/AdminUser");
  const Comment = require("../../models/Comment");
  const loginMiddleware = require("../../middleware/loginMiddleware");
  const router = express.Router({
    mergeParams: true,
    useUnifiedTopology: true,
  });

  // 创建菜单
  router.post("/", loginMiddleware(), async (req, res) => {
    const model = await req.Model.create(req.body);
    res.send(model);
  });
  // 管理员账号创建
  router.post("/register", async (req, res) => {
    const account = await req.Model.find({ account: req.body.account });
    if (account.length != 0) {
      res.send({ status: 401, msg: "该用户已被注册哦~" });
    } else {
      console.log(req.Model);
      const model = await req.Model.create(req.body);
      res.send({ data: model, status: 200, msg: "创建成功！" });
    }
  });
  // 用户注册
  // router.post('/register', async(req, res) => {
  //         const model = await req.Model.create(req.body)
  //         res.send(model)
  //     })
  // 查询接口
  router.get("/", async (req, res) => {
    let data = {};
    // 用户传递的页码
    let page = req.query.page || 1;
    // 每页条数
    let size = parseInt(req.query.size) || 10;
    // 总条数
    let total = await req.Model.countDocuments();
    // 总页数
    let pages = Math.ceil(total / size);
    let start = (page - 1) * size;
    const items = await req.Model.find()
      .sort({ _id: -1 })
      .limit(size || 10)
      .skip(start);
    data.items = items;
    (data.total = total), (data.pages = pages);
    res.send(data);
  });
  // 查询文章
  router.get("/art", async (req, res) => {
    let data = {};
    // 用户传递的页码
    let page = req.query.page || 1;
    // 每页条数
    let size = parseInt(req.query.size) || 10;
    // 总条数
    let total = await req.Model.countDocuments(req.query);
    // 总页数
    let pages = Math.ceil(total / size);
    let start = (page - 1) * size;
    const items = await req.Model.find(req.query)
      .populate("classId")
      .sort({ _id: -1 })
      .limit(size || 10)
      .skip(start);
    data.items = items;
    data.total = total;
    data.pages = pages;
    res.send(data);
  });
  // 修改文章状态
  router.put("/art/:id", loginMiddleware(), async (req, res) => {
    await req.Model.findByIdAndUpdate(req.params.id, req.body);
    res.send({
      msg: "操作成功！",
      status: 200,
    });
  });
  // 查询某篇文章
  router.get("/art/:id", async (req, res) => {
    const items = await req.Model.findById(req.params.id);
    res.send(items);
  });
  // 添加评论
  router.post("/addcomment", async (req, res) => {
    let data = {};
    // 用户传递的页码
    let page = req.body.page || 1;
    // 每页条数
    let pagesize = 10;
    // 总条数
    let total = await req.Model.countDocuments({});
    // 总页数
    let start = (page - 1) * pagesize;
    let items = [];
    const model = await req.Model.create(req.body);
    res.send(model);
  });
  // 查询评论
  router.get("/comment", async (req, res) => {
    let data = {};
    // 用户传递的页码
    let page = req.query.page;
    // 每页条数
    let pagesize = 10;
    // 总页数
    let start = (page - 1) * pagesize;
    let items;
    items = await req.Model.find({ parentId: "0" })
      .populate(["Aid", "Uid"])
      .sort({ _id: -1 })
      .limit(pagesize)
      .skip(start)
      .select("-__v")
      .lean();
    // 总条数
    let total = await req.Model.find({ parentId: "0" }).count();
    // 处理异步回调
    let promises = items.map((item) => {
      return req.Model.find({
        parentId: item._id,
      })
        .select("-__v")
        .lean();
    });
    var list = await Promise.all(promises);
    items.forEach((item) => {
      list.forEach((code) => {
        if (code.length > 0 && item._id == code[0].parentId) {
          item.lists = code;
        }
      });
    });
    data.items = items;
    data.total = total;
    res.send(data);
  });
  // 查询评论
  router.get("/comment/:id", async (req, res) => {
    let data = {};
    // 用户传递的页码
    let page = req.query.page;
    // 每页条数
    let pagesize = 10;
    // 总页数
    let start = (page - 1) * pagesize;
    let items;
    items = await req.Model.find({ Aid: req.params.id, parentId: "0" })
      .populate(["Aid", "Uid"])
      .sort({ _id: -1 })
      .limit(pagesize)
      .skip(start)
      .select("-__v")
      .lean();
    // 总条数
    let total = await req.Model.find({
      Aid: req.params.id,
      parentId: "0",
    }).count();
    // 处理异步回调
    let promises = items.map((item) => {
      return req.Model.find({
        parentId: item._id,
      })
        .select("-__v")
        .lean();
    });
    var list = await Promise.all(promises);
    items.forEach((item) => {
      list.forEach((code) => {
        if (code.length > 0 && item._id == code[0].parentId) {
          item.lists = code;
        }
      });
    });
    data.items = items;
    data.total = total;
    res.send(data);
  });

  // 查询单条数据
  router.get("/:id", async (req, res) => {
    let num = await Comment.find({ Aid: req.params.id, parentId: "0" }).count();
    const items = await req.Model.findByIdAndUpdate(req.params.id, {
      $inc: { visited: +1 },
      accessPulish_count: num,
    });
    res.send(items);
  });
  // 查询分类文章
  router.get("/class/:id", async (req, res) => {
    let data = {};
    let page = req.query.page;
    // 每页条数
    let pagesize = 10;
    // 总条数
    let total = await req.Model.countDocuments({ classId: req.params.id });
    let start = (page - 1) * pagesize;
    const items = await req.Model.find({ classId: req.params.id })
      .populate("classId")
      .limit(pagesize)
      .skip(start);
    data.items = items;
    data.total = total;
    res.send(data);
  });
  // 修改菜单
  router.put("/:id", loginMiddleware(), async (req, res) => {
    await req.Model.findByIdAndUpdate(req.params.id, req.body);
    res.send({
      msg: "操作成功！",
      status: 200,
    });
  });

  // 删除菜单
  router.delete("/:id", loginMiddleware(), async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id);
    res.send({
      msg: "删除成功",
      status: 200,
    });
  });

  app.use(
    "/admin/api/rest/:resource",
    async (req, res, next) => {
      const modelName = require("inflection").classify(req.params.resource);
      req.Model = require(`../../models/${modelName}`);
      next();
    },
    router
  );
  // 上传图片
  const multer = require("multer");
  const upload = multer({ dest: __dirname + "/../../uploads" });
  app.post(
    "/admin/api/upload",
    loginMiddleware(),
    upload.single("file"),
    async (req, res) => {
      const file = req.file;
      file.url = `http://www.zhengwei66.cn/uploads/${file.filename}`;
      res.send(file);
    }
  );
  // 登录
  app.post(
    "/admin/api/login",
    async (req, res) => {
      // 获取用户名和密码
      const { account, password } = req.body;
      // 根据用户名查找用户
      const user = await AdminUser.findOne({ account }).select("+password");
      assert(user, 400, "用户不存在!");
      if (user.power == 2) {
        res.send({ status: 401, msg: "用户已被冻结！" });
      }
      // 校验密码
      const isValid = require("bcrypt").compareSync(password, user.password);
      assert(isValid, 400, "密码错误!");
      const token = jwt.sign({ id: user._id }, app.get("secret"));
      return res.send({ token, data: user });
    },
    router
  );

  // 错误处理的中间件
  app.use(async (err, req, res, next) => {
    res.status(err.statusCode || 500).send(err.message);
  });
};
